# clear and libraries
rm(list=ls())
packs = c('tidyverse', 'stringr', 'lubridate', 'igraph',
          'hrbrthemes')
source("r/helpers.R")
loadPkg(packs)

# load data
load('repFile/data/network-data.rda')


# create network graph
GrSoc = function(x){
  el_bor = cbind(x$code3,as.character(x$G.G2.G2B_Code2))
  el_bor2 = cbind(x$code3,as.character(x$G.G3.G3B_Code2))
  el_vis = cbind(x$code3,as.character(x$I.I7.I7B_Code2))
  
  el = rbind(el_bor, el_bor2, el_vis)
  el = el[complete.cases(el),]
  
  # get graph
  gr = graph_from_edgelist(el,directed=TRUE)
  return(gr)
}


#create "graphs" for each set of questions
SocList = plyr::dlply(dat, 'A.A7', function(x) GrSoc(x))


# back out centrality
get_central = function(neigh_graph) 
{
  # initialize dataframe
  respondent_frame = data.frame(code3 = names(V(neigh_graph)))
  
  # calculate centrality
  degree = degree(neigh_graph, mode = 'in')
  
  # attach to dataframe
  respondent_frame = 
    add_column(respondent_frame, degree)
}


# get centrality 
central_Soc = 
  map(SocList, get_central) %>% 
  do.call('rbind', .) %>% 
  mutate(code3 = as.character(code3)) %>% 
  setNames(paste0('soc_', names(.))) %>% 
  dplyr::rename(code3 = soc_code3)


# merge back into dataset
modDat = 
  left_join(dat, central_Soc)


# get rid of DK/RF
modDat[modDat == 888] <- NA
modDat[modDat == 999] <- NA

# social density variable
modDat$p_id = 1:nrow(modDat)

socLat = 
  modDat %>% 
  select(I.I6_Community.work, I.I8_Help.each.other, p_id) %>% 
  na.omit

socFrame = data.frame(p_id = socLat$p_id, 
                      socLat = prcomp(socLat[,1:2], scale. = TRUE)$x[,'PC1']*-1)

modDat =
  left_join(modDat, socFrame)



# output
m1 =lm(soc_degree ~ socLat + C.C4_Age + C.C5_Gender + C.C6 + factor(City), 
       data = modDat)

stargazer(m1, style = 'ajps', 
          intercept.bottom = F, 
          covariate.labels = c('Intercept', 'Social Connectedness', 
                               'Age', 'Gender'), 
          title = 'Network model predicing social in-degree with social connectedness measure. Includes controls for religion and survey wave.', 
          label = 'network', 
          omit = c('factor', 'C.C6'),
          dep.var.labels = c('Social in-degree'),
          out = 'repFile/paper/figures/network.tex')
